
local toolkits = require("tools/toolkits")

modimport("scripts/tools/iai_cook_fn")

local containers = require("containers")
local pots = { "cookpot", "portablecookpot", "portablespicer" }

for i, n in pairs(pots) do
    containers.params[n].acceptsstacks = true

	AddPrefabPostInit(n, function(inst)
		if not TheWorld.ismastersim then return end
        --hook
		toolkits.hookfn(inst.components.container, "GiveItem", function(storage, self, item, slot, ...)
			storage.item = item.prefab
            storage.aver = slot == nil
			return self, item, slot, ...
		end, function(storage, self, success)
			if success and storage.aver then
				local items = self:FindItems(function(item)
					if item.prefab == storage.item and item.components.stackable then 
						return true
					else 
						return false
					end
				end)
				local totalsize = 0
				local num = 0
				for i, n in pairs(items) do
					totalsize = totalsize + n.components.stackable:StackSize()
					num = num + 1
				end
				local averagesize = math.floor(totalsize/num)
				local extrasize = totalsize%num
				for i, n in pairs(items) do
					local t = extrasize > 0 and averagesize + 1 or averagesize
					n.components.stackable:SetStackSize(t)
					extrasize = extrasize - 1
				end
			end
			return success
		end)

	end)
end
